﻿using Orchard;
using Orchard.FileSystems.Media;
using Orchard.Localization;
using Orchard.Media.Services;
using Orchard.Mvc;
using Orchard.Security;
using System;
using System.IO;
using System.Web;
using System.Web.Mvc;
namespace CKEditor.Controllers
{
    public class UploadController : Controller
    {
        private static readonly string wikiImagePath = "Wiki";

        private Localizer T { get; set; }

        private readonly IOrchardServices _services;
        private readonly IAuthenticationService _authenticationService;
        private readonly IMediaService _mediaService;
        private readonly IStorageProvider _storageProvider;
        public UploadController(IAuthenticationService authenticationService,
                            IMediaService mediaService,
                            IStorageProvider storageProvider,
                            IOrchardServices services)
        {
            this._authenticationService = authenticationService;
            this._mediaService = mediaService;
            this._storageProvider = storageProvider;
            this._services = services;
            T = NullLocalizer.Instance;
        }

        public ActionResult WikiImage()
        {
            return new ShapeResult(this, _services.New.Wiki_Image());
        }

        [HttpPost]
        public ActionResult WikiImage(HttpPostedFileBase upload, string CKEditorFuncNum, string CKEditor, string langCode)
        {
            string vImagePath = String.Empty;
            string vMessage = String.Empty;
            string vFilePath = String.Empty;
            string vOutput = String.Empty;

            try
            {
                if (upload != null && upload.ContentLength > 0)
                {
                    var vFileName = DateTime.Now.ToString("yyyyMMdd-HHMMssff") +
                                    Path.GetExtension(upload.FileName).ToLower();

                    EnsurePath(wikiImagePath);

                    vFilePath = _storageProvider.Combine(wikiImagePath, vFileName);
                    upload.SaveAs(vFilePath);

                    vImagePath = _storageProvider.GetPublicUrl(vFilePath);
                    vMessage = T("Image was saved correctly").Text;
                }
            }
            catch
            {
                vMessage = "There was an issue uploading";
            }

            vOutput = @"<html><body><script>window.parent.CKEDITOR.tools.callFunction(" + CKEditorFuncNum + ", \"" + vImagePath + "\", \"" + vMessage + "\");</script></body></html>";

            return Content(vOutput);

        }
        private void EnsurePath(string path)
        {
            try
            {
                _mediaService.GetMediaFiles(path);
            }
            catch
            {
                _mediaService.CreateFolder("", path);
            }
        }
    }
}